package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.zzyl.dto.NursingPlanDTO;
import com.zzyl.entity.NursingPlan;
import com.zzyl.entity.NursingProject;
import com.zzyl.entity.NursingProjectPlan;
import com.zzyl.mapper.NursingPlanMapper;
import com.zzyl.mapper.NursingProjectMapper;
import com.zzyl.mapper.NursingProjectPlanMapper;
import com.zzyl.service.NursingPlanService;
import com.zzyl.vo.NursingPlanDetailVO;
import com.zzyl.vo.NursingPlanVO;
import com.zzyl.vo.ProjectPlanItemVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class NursingPlanServiceImpl implements NursingPlanService {

    private final NursingPlanMapper nursingPlanMapper;

    private final NursingProjectPlanMapper nursingProjectPlanMapper;

    private final NursingProjectMapper nursingProjectMapper;

    /**
     * 查询全部计划
     *
     * @return
     */
    @Override
    public List<NursingPlanVO> getAllNursingPlan() {
        List<NursingPlan> nursingPlans = nursingPlanMapper.selectAllNursingPlan();
        return nursingPlans
                .stream()
                .map(nursingPlan -> {
                    NursingPlanVO nursingPlanVO = new NursingPlanVO();
                    BeanUtil.copyProperties(nursingPlan, nursingPlanVO);
                    return nursingPlanVO;
                }).collect(Collectors.toList());
    }

    /**
     * 分页查询
     *
     * @param name
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<NursingPlanVO> searchNursingPlan(String name, Integer status, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<NursingPlan> list = nursingPlanMapper.selectPage(name, status);
        List<NursingPlanVO> nursingPlanVOS = BeanUtil.copyToList(list, NursingPlanVO.class);
        return new PageInfo<>(nursingPlanVOS);
    }

    /**
     * 新增
     *
     * @param nursingPlanDTO
     */
    @Override
    public void add(NursingPlanDTO nursingPlanDTO) {
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtil.copyProperties(nursingPlanDTO, nursingPlan);
        nursingPlanMapper.insertNursingPlan(nursingPlan);

        log.info("plan_id是: {}", nursingPlan.getId());

        Integer planId = nursingPlan.getId();

        //保存护理项目_计划表
        List<ProjectPlanItemVO> projectPlans = nursingPlanDTO.getProjectPlans();
        if (projectPlans != null && !projectPlans.isEmpty()) {
            List<NursingProjectPlan> plans = projectPlans.stream().map(item -> {
                NursingProjectPlan p = new NursingProjectPlan();
                p.setPlanId(planId);
                p.setProjectId(item.getProjectId().intValue()); // 注意 Long → Integer
                p.setExecuteTime(item.getExecuteTime());
                p.setExecuteCycle(item.getExecuteCycle());
                p.setExecuteFrequency(item.getExecuteFrequency());
                // 如果有创建人等字段，也设置一下
                return p;
            }).collect(Collectors.toList());

            // 批量插入中间表
            nursingProjectPlanMapper.batchInsert(plans);
        }
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        nursingPlanMapper.deleteById(id);
    }

    /**
     * 启用禁用
     *
     * @param id
     * @param status
     */
    @Override
    public void startAndStop(Long id, Integer status) {
        nursingPlanMapper.updateStatusById(id, status);
    }

    /**
     * 根据id查询
     *
     * @param planId
     * @return
     */
    @Override
    @Transactional
    public NursingPlanDetailVO getPlanDetailById(Integer planId) {
        // 1. 查询主计划
        NursingPlan plan = nursingPlanMapper.selectById(planId);

        // 2. 查询关联的项目计划
        List<NursingProjectPlan> projectPlanList = nursingProjectPlanMapper.selectByPlanId(planId);

        // 3. 获取所有 projectId
        List<Integer> projectIds = projectPlanList.stream()
                .map(NursingProjectPlan::getProjectId)
                .distinct()
                .collect(Collectors.toList());

        // 4. 批量查询项目信息
        final Map<Integer, NursingProject> projectMap = new HashMap<>();
        if (!projectIds.isEmpty()) {
            List<NursingProject> projects = nursingProjectMapper.selectBatchIds(projectIds);
            projectMap.putAll(projects.stream().collect(Collectors.toMap(p -> p.getId().intValue(), p -> p)));
        }

        // 5. 组装 projectPlans
        List<ProjectPlanItemVO> itemVOs = projectPlanList.stream().map(pp -> {
            ProjectPlanItemVO vo = new ProjectPlanItemVO();
            vo.setId(pp.getId());
            vo.setPlanId(pp.getPlanId());
            vo.setProjectId(pp.getProjectId());
            vo.setExecuteTime(pp.getExecuteTime());
            vo.setExecuteCycle(pp.getExecuteCycle());
            vo.setExecuteFrequency(pp.getExecuteFrequency());
            vo.setCreateTime(pp.getCreateTime());

            // 设置项目名称
            NursingProject project = projectMap.get(pp.getProjectId());
            vo.setProjectName(project != null ? project.getName() : "未知项目");

            return vo;
        }).collect(Collectors.toList());

        // 6. 组装主 VO
        NursingPlanDetailVO result = new NursingPlanDetailVO();
        result.setId(plan.getId());
        result.setSortNo(plan.getSortNo());
        result.setPlanName(plan.getPlanName());
        result.setStatus(plan.getStatus());
        result.setCreateTime(plan.getCreateTime());
        result.setUpdateTime(plan.getUpdateTime());
        result.setCreateBy(plan.getCreateBy());
        result.setRemark(plan.getRemark());
        result.setProjectPlans(itemVOs);

        return result;
    }

    /**
     * 修改
     * @param id
     */
    @Override
    @Transactional
    public void update(Integer id, NursingPlanDTO nursingPlanDTO) {
        Integer planId = nursingPlanDTO.getId();
        if (planId == null) {
            throw new IllegalArgumentException("计划ID不能为空");
        }
        // 1. 更新主表
        NursingPlan plan = new NursingPlan();
        plan.setId(planId);
        plan.setPlanName(nursingPlanDTO.getPlanName());
        plan.setSortNo(nursingPlanDTO.getSortNo());
        plan.setRemark(nursingPlanDTO.getRemark());
        plan.setStatus(nursingPlanDTO.getStatus());
        plan.setUpdateTime(LocalDateTime.now());

        nursingPlanMapper.updateById(plan);

        // 2. 删除旧的子项
        nursingProjectPlanMapper.deleteByPlanId(planId);

        // 3. 插入新的子项
        List<ProjectPlanItemVO> projectPlans = nursingPlanDTO.getProjectPlans();
        if (!CollectionUtils.isEmpty(projectPlans)) {
            List<NursingProjectPlan> items = projectPlans.stream()
                    .map(vo -> {
                        NursingProjectPlan item = new NursingProjectPlan();
                        item.setPlanId(planId);
                        item.setProjectId(vo.getProjectId());
                        item.setExecuteTime(vo.getExecuteTime());
                        item.setExecuteCycle(vo.getExecuteCycle());
                        item.setExecuteFrequency(vo.getExecuteFrequency());
                        item.setRemark(vo.getRemark());
                        item.setCreateTime(LocalDateTime.now());
                        return item;
                    })
                    .collect(Collectors.toList());

            nursingProjectPlanMapper.batchInsert(items);
        }
    }
}
